package com.wfh.rpc.loadbalancer;

import com.wfh.rpc.model.ServiceModelInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Title: RoundRobinLoadBalancer
 * @Author wangfenghuan
 * @Package com.wfh.rpc.loadbalancer
 * @Date 2025/10/16 20:58
 * @description: 轮询负载均衡器
 */
public class RoundRobinLoadBalancer implements LoadBalancer{

    /**
     * 当前轮询的下标
     */
    private final AtomicInteger currentIndex = new AtomicInteger(0);

    @Override
    public ServiceModelInfo select(Map<String, Object> requestParams, List<ServiceModelInfo> serviceModelInfoList) {

        if (serviceModelInfoList.isEmpty()){
            return null;
        }
        // 只有一个服务，不需要轮询
        int size = serviceModelInfoList.size();
        if (size == 1){
            return serviceModelInfoList.get(0);
        }
        // 取模算法轮询
        int index = currentIndex.getAndIncrement() % size;
        return serviceModelInfoList.get(index);
    }
}
